package org.kiwi.job.component;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @email jack.liu.19910921@gmail.com
 * Created by jack on 17/2/19.
 */
@Component
public class RedisCacheManager {

    private static final String DEFAULT_CACHE_PREFIX = "org.kiwi.job.";

    @Autowired
    private RedisTemplate redisTemplate;

    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(this.getCacheKey(key), value);
    }

    public void set(String key, Object value, long timeout, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(this.getCacheKey(key), value, timeout, timeUnit);
    }

    public <T> T getAndSet(String key, T value) {
        return (T) redisTemplate.opsForValue().getAndSet(this.getCacheKey(key), value);
    }

    public boolean setNX(String key, Object value) {
        return redisTemplate.opsForValue().setIfAbsent(this.getCacheKey(key), value);
    }

    public boolean setNX(String key, Object value, long timeout, TimeUnit timeUnit) {
        key = this.getCacheKey(key);
        boolean res = redisTemplate.opsForValue().setIfAbsent(key, value);
        if (res) {
            redisTemplate.expire(key, timeout, timeUnit);
        }
        return res;
    }

    public Object get(String key) {
        return redisTemplate.opsForValue().get(this.getCacheKey(key));
    }

    public <T> T get(String key, Class<T> tClass) {
        return (T) redisTemplate.opsForValue().get(this.getCacheKey(key));
    }

    public void delete(String key) {
        redisTemplate.delete(this.getCacheKey(key));
    }

    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    protected String getCachePrefix() {
        return DEFAULT_CACHE_PREFIX;
    }

    String getCacheKey(String key) {
        return StringUtils.startsWith(key, getCachePrefix()) ? key : getCachePrefix() + key;
    }

}
